import request from '@/common/request/index.js'
import utils from '@/common/utils/index.js'
import store from '@/common/store/index.js'
import { BASE_URL, SIGN } from '@/env.js'
const jweixin = require('jweixin-module')

// 微信公众号分享
const wxoaShare = () => {
	// #ifdef H5
	const spm = store.state.user.userInfo?.id ? `${store.state.user?.userInfo?.id}.1.0.2.1` : ""
	const title = store.state.config?.share?.title ? store.state.config?.share?.title : ""
	const imgUrl = store.state.config?.share?.image ? store.state.config?.share?.image : ""
	const desc = store.state.config?.share?.description ? store.state.config?.share?.description : ""
	const uri = window.location.origin + window.location.pathname
	const curi = window.location.hash.indexOf('/pages/video/play')
	const link = curi != -1 ? `${window.location.href}?scene=${spm}` : uri + `?${SIGN}#/pages/home/index?scene=${spm}`
	// if(window.location.hash.indexOf('/pages/video/play') != -1) {
	// 	link = `${window.location.href}?scene=${spm}`
	// } else {
	// 	link = uri + `?${SIGN}#/pages/home/index?scene=${spm}`
	// }

	request('user.share', { uri }).then(res => {
		if(res.code === 1) {
			console.log("获取分享配置");
			jweixin.config({
				debug: false,
				appId: res.data.appId,
				nonceStr: res.data.nonceStr,
				timestamp: res.data.timestamp,
				signature: res.data.signature,
				jsApiList: [
					'updateAppMessageShareData',
					'updateTimelineShareData',
				]
			})
			jweixin.ready(() => {
				// true(已登录) false(未登录)
				store.commit('app/setJwx', spm ? true : false)
				// 分享给朋友
				jweixin.updateAppMessageShareData({ 
					title,
					desc,
					link,
					imgUrl,
					success: e => {
						console.log(e, "分享好友");
					}
				})
				// 分享朋友圈
				jweixin.updateTimelineShareData({
					title,
					link,
					imgUrl,
					success: e => {
						console.log(e, "分享朋友圈");
					}
				})
			})
			jweixin.error(e => {
				console.log(e, '微信分享config信息验证失败');
			})
		}
	})
	// #endif
}

// 分享工具类
class ShareUtils {
	/**
	 * 生成分享链接
	 * @param {Object} params - 分享参数
	 * @param {string} params.videoId - 视频ID
	 * @param {string} params.spm - 分享来源标识
	 * @param {string} params.path - 分享路径，默认为 '/pages/video/play'
	 * @returns {string} 分享链接
	 */
	static getShareUrl({ videoId, spm, path = '/pages/video/play' }) {
		const origin = typeof window !== 'undefined' ? window.location.origin : ''
		const sharePath = `${path}?scene=${spm}&id=${videoId}`
		return origin ? origin + sharePath : sharePath
	}

	/**
	 * Facebook分享
	 * @param {Object} params - 分享参数
	 * @param {string} params.url - 分享链接
	 * @param {string} params.title - 分享标题
	 * @param {Function} params.onClose - 关闭回调
	 * @param {Function} params.request - 请求方法
	 */
	static shareToFacebook({ url, title, onClose, request }) {
		const encodedUrl = encodeURIComponent(url)
		const encodedText = encodeURIComponent(title)
		const shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}&quote=${encodedText}`
		window.open(shareUrl, '_blank')
		
		// 调用分享成功接口
		if (request) {
			this.callShareSuccess(request)
		}
		
		if (onClose) onClose()
	}

	/**
	 * WhatsApp分享
	 * @param {Object} params - 分享参数
	 * @param {string} params.url - 分享链接
	 * @param {string} params.title - 分享标题
	 * @param {Function} params.onClose - 关闭回调
	 * @param {Function} params.request - 请求方法
	 */
	static shareToWhatsApp({ url, title, onClose, request }) {
		const text = `${title} ${url}`
		const shareUrl = `https://api.whatsapp.com/send?text=${encodeURIComponent(text)}`
		window.open(shareUrl, '_blank')
		
		// 调用分享成功接口
		if (request) {
			this.callShareSuccess(request)
		}
		
		if (onClose) onClose()
	}

	/**
	 * 复制链接到剪贴板
	 * @param {Object} params - 复制参数
	 * @param {string} params.url - 要复制的链接
	 * @param {Function} params.onSuccess - 成功回调
	 * @param {Function} params.onError - 错误回调
	 * @param {Function} params.onClose - 关闭回调
	 * @param {Function} params.request - 请求方法
	 */
	static copyLink({ url, onSuccess, onError, onClose, request }) {
		// 首选异步剪贴板
		if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(url).then(() => {
				// 调用分享成功接口
				if (request) {
					this.callShareSuccess(request)
				}
				if (onSuccess) onSuccess('链接已复制')
				if (onClose) onClose()
			}).catch(() => {
				this.fallbackCopy({ text: url, onSuccess, onError, onClose, request })
			})
		} else {
			this.fallbackCopy({ text: url, onSuccess, onError, onClose, request })
		}
	}

	/**
	 * 复制降级方案
	 * @param {Object} params - 复制参数
	 * @param {string} params.text - 要复制的文本
	 * @param {Function} params.onSuccess - 成功回调
	 * @param {Function} params.onError - 错误回调
	 * @param {Function} params.onClose - 关闭回调
	 * @param {Function} params.request - 请求方法
	 */
	static fallbackCopy({ text, onSuccess, onError, onClose, request }) {
		try {
			const textarea = document.createElement('textarea')
			textarea.value = text
			textarea.setAttribute('readonly', '')
			textarea.style.position = 'absolute'
			textarea.style.left = '-9999px'
			document.body.appendChild(textarea)
			textarea.select()
			document.execCommand('copy')
			document.body.removeChild(textarea)
			
			// 调用分享成功接口
			if (request) {
				this.callShareSuccess(request)
			}
			
			if (onSuccess) onSuccess('链接已复制')
			if (onClose) onClose()
		} catch (e) {
			if (onError) onError('复制失败，请手动复制')
		}
	}

	/**
	 * 调用分享成功接口
	 * @param {Function} request - 请求方法
	 */
	static async callShareSuccess(request) {
		try {
			await request('share.success', {
				share_type: 'share_wx_after'
			}, false)
		} catch (error) {
			console.log('分享成功回调失败:', error)
		}
	}
}

export { ShareUtils }
export default wxoaShare
